package com.exam.sacrifice.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatImageView;

public class GradientAlphaImageView extends AppCompatImageView {
    private Paint paint;
    private RadialGradient gradient;
    private int width, height;

    public GradientAlphaImageView(Context context) {
        super(context);
        init();
    }

    public GradientAlphaImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public GradientAlphaImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // 使用DST_IN模式，只显示源图像与渐变重叠的部分
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        // 创建径向渐变，从中心不透明到边缘透明
        gradient = new RadialGradient(
                w / 2f, h / 2f, Math.max(w, h) / 2f,
                new int[]{Color.BLACK, Color.TRANSPARENT},
                new float[]{0f, 1f},
                Shader.TileMode.CLAMP);
        paint.setShader(gradient);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 先保存图层
        int saved = canvas.saveLayer(0, 0, width, height, null);
        // 绘制原始图片
        super.onDraw(canvas);
        // 应用渐变遮罩
        canvas.drawRect(0, 0, width, height, paint);
        // 恢复图层
        canvas.restoreToCount(saved);
    }
}